﻿using System;
using System.Text;
using System.Data;
using System.Windows;
using System.Data.SqlClient;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;

namespace LEDShow.Helpers
{
    public class SqlDataLayer
    {
        public static string _conStr = null;

        public static string ConnStr
        {
            get
            {
                if (null == _conStr)
                {
                    _conStr = string.Format(
                    "server={0};uid={1};pwd={2};database={3};",
                    ConfigurationManager.AppSettings["Server"].ToString(),
                    ConfigurationManager.AppSettings["uid"],
                    ConfigurationManager.AppSettings["pwd"].ToString(),
                    ConfigurationManager.AppSettings["Database"].ToString()
                    );
                }
                return _conStr;
            }

        }
        
        private SqlConnection MyCon = null;
        public SqlDataLayer()
        {
            //ConnStr = string.Format(
            //    "server={0};uid={1};pwd={2};database={3};",
            //    ConfigurationManager.AppSettings["Server"].ToString(), 
            //    ConfigurationManager.AppSettings["uid"],
            //    ConfigurationManager.AppSettings["pwd"].ToString(),
            //    ConfigurationManager.AppSettings["Database"].ToString()
            //    );
        }

        public bool MyOpen()
        {
            MyCon = new SqlConnection(ConnStr);
            try
            {
                MyCon.Open();
            }
            catch (System.Exception e)
            {
                MessageBox.Show(e.ToString());
                return false;
            }
            return true;
        }

        public bool MyClose()
        {
            try
            {
                if (MyCon != null)
                    MyCon.Close();
            }
            catch (System.Exception e)
            {
                MessageBox.Show(e.ToString());
                return false;
            }
            return true;
        }

        /// <summary>
        /// 使用对象中存在的连接  所以不需要在创建连接了
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public bool ExecuteNonQueryWithNoConn(string sql)
        {
            try
            {
                SqlCommand cmd = new SqlCommand(sql, MyCon);
                cmd.ExecuteNonQuery();
                return true;
            }
            catch (System.Exception e)
            {
                MessageBox.Show(e.ToString());
                return false;
            }
        }


        /// <summary>
        /// 根据日期线路查询该日使用的时刻表
        /// </summary>
        /// <param name="mydate"></param>
        /// <param name="strline"></param>
        /// <returns>不存在就返回空  否则返回时刻表名</returns>
        public string SelectTableToDate(string mydate,string strline)
        {
            string sql = "select TableInfo.TableName from TableToDate  left join TableInfo on TableToDate.TableInfo_id = TableInfo.ID where TableToDate.AssignDate='"
                        + mydate + "' and TableInfo.LineID ='" + strline + "'";
            DataTable tempdt = SelectDt(sql);
            if (tempdt!=null&&tempdt.Rows.Count==1)
            {
                return tempdt.Rows[0]["TableName"].ToString();
            }
            else
            {
                return "";
            }
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="tablename"></param>
        /// <param name="field"></param>
        /// <param name="content"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public bool UpdateTableField(string tablename,string field,string content,string condition)
        {
            string sqlString = "select * from " + tablename + " where " + condition;

            return true;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="tablename"></param>
        /// <param name="fields"></param>
        /// <param name="contents"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public bool UpdateTableFields(string tablename,string[] fields,string[] contents,string condition)
        {
            return true;
        }


        #region 创建 Connection 和 Command

        private IDbConnection GetConnection()
        {
            return new System.Data.SqlClient.SqlConnection(ConnStr);
        }


        private IDbCommand GetCommand(string Sql, IDbConnection iConn)
        {
            return new System.Data.SqlClient.SqlCommand(Sql, (SqlConnection)iConn);
        }

        private IDbCommand GetCommand()
        {
            return new System.Data.SqlClient.SqlCommand();
        }

        private IDataAdapter GetAdapater(string Sql, IDbConnection iConn)
        {
            return new System.Data.SqlClient.SqlDataAdapter(Sql, (SqlConnection)iConn);

        }

        private IDataAdapter GetAdapater()
        {
            return new System.Data.SqlClient.SqlDataAdapter();
        }

        private IDataAdapter GetAdapater(IDbCommand iCmd)
        {
            return new System.Data.SqlClient.SqlDataAdapter((SqlCommand)iCmd);
        }
        #endregion

        #region  执行简单SQL语句
        /// <summary>
        /// 执行SQL语句，返回影响的记录数
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public int ExecuteSql(string SqlString)
        {
            using (System.Data.IDbConnection iConn = this.GetConnection())
            {
                using (System.Data.IDbCommand iCmd = GetCommand(SqlString, iConn))
                {
                    iConn.Open();
                    try
                    {
                        int rows = iCmd.ExecuteNonQuery();
                        return rows;
                    }
                    catch (System.Exception E)
                    {
                        throw new Exception(E.Message);
                        return -1;
                    }
                    finally
                    {
                        if (iConn.State != ConnectionState.Closed)
                        {
                            iConn.Close();
                        }
                    }
                }
            }
        }


        public bool CreateTable(string SqlString)
        {
            using(System.Data.IDbConnection iConn=this.GetConnection())
            {
                using(System.Data.IDbCommand iCmd=this.GetCommand(SqlString,iConn))
                {
                    iConn.Open();
                    try
                    {
                        iCmd.ExecuteNonQuery();
                        return true;
                    }
                    catch
                    {
                        return false;
                    }
                    finally
                    {
                        if (iConn.State != ConnectionState.Closed)
                        {
                            iConn.Close();
                        }
                    }
                }
            }
        }

        /**/
        /// <summary>
        /// 执行多条SQL语句，实现数据库事务。
        /// </summary>
        /// <param name="SQLStringList">多条SQL语句</param>        
        public bool ExecuteSqlTran(ArrayList SQLStringList)
        {
            bool result = true;

            using (System.Data.IDbConnection iConn = this.GetConnection())
            {
                iConn.Open();
                using (System.Data.IDbCommand iCmd = GetCommand())
                {
                    iCmd.Connection = iConn;
                    using (System.Data.IDbTransaction iDbTran = iConn.BeginTransaction())
                    {
                        iCmd.Transaction = iDbTran;
                        try
                        {
                            for (int n = 0; n < SQLStringList.Count; n++)
                            {
                                string strsql = SQLStringList[n].ToString();
                                if (strsql.Trim().Length > 1)
                                {
                                    iCmd.CommandText = strsql;
                                    iCmd.ExecuteNonQuery();
                                }
                            }
                            iDbTran.Commit();
                        }
                        catch (System.Exception E)
                        {
                            iDbTran.Rollback();
                            result = false;
                            throw new Exception(E.Message);
                        }
                        finally
                        {
                            if (iConn.State != ConnectionState.Closed)
                            {
                                iConn.Close();
                            }
                        }
                    }

                }
            }
            return result;
        }
        /**/
        /// <summary>
        /// 执行带一个存储过程参数的的SQL语句。
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <param name="content">参数内容,比如一个字段是格式复杂的文章，有特殊符号，可以通过这个方式添加</param>
        /// <returns>影响的记录数</returns>
        public int ExecuteSql(string SqlString, string content)
        {
            using (System.Data.IDbConnection iConn = this.GetConnection())
            {
                using (System.Data.IDbCommand iCmd = GetCommand(SqlString, iConn))
                {
                    System.Data.IDataParameter myParameter = new SqlParameter("@content", SqlDbType.Text);  //this.iDbPara("@content", "text");
                    myParameter.Value = content;
                    iCmd.Parameters.Add(myParameter);
                    iConn.Open();
                    try
                    {
                        int rows = iCmd.ExecuteNonQuery();
                        return rows;
                    }
                    catch (System.Exception e)
                    {
                        throw new Exception(e.Message);
                    }
                    finally
                    {
                        if (iConn.State != ConnectionState.Closed)
                        {
                            iConn.Close();
                        }
                    }
                }
            }
        }


        /**/
        /// <summary>
        /// 向数据库里插入图像格式的字段(和上面情况类似的另一种实例)
        /// </summary>
        /// <param name="strSQL">SQL语句</param>
        /// <param name="fs">图像字节,数据库的字段类型为image的情况</param>
        /// <returns>影响的记录数</returns>
        public int ExecuteSqlInsertImg(string SqlString, byte[] fs)
        {
            using (System.Data.IDbConnection iConn = this.GetConnection())
            {
                using (System.Data.IDbCommand iCmd = GetCommand(SqlString, iConn))
                {
                    System.Data.IDataParameter myParameter = new SqlParameter("@content", SqlDbType.Image); //this.iDbPara("@content", "image");
                    myParameter.Value = fs;
                    iCmd.Parameters.Add(myParameter);
                    iConn.Open();
                    try
                    {
                        int rows = iCmd.ExecuteNonQuery();
                        return rows;
                    }
                    catch (System.Exception e)
                    {
                        throw new Exception(e.Message);
                    }
                    finally
                    {
                        if (iConn.State != ConnectionState.Closed)
                        {
                            iConn.Close();
                        }
                    }
                }
            }
        }

        /**/
        /// <summary>
        /// 执行一条计算查询结果语句，返回查询结果（object）。
        /// </summary>
        /// <param name="SQLString">计算查询结果语句</param>
        /// <returns>查询结果（object）</returns>
        public object GetSingle(string SqlString)
        {
            using (System.Data.IDbConnection iConn = GetConnection())
            {
                using (System.Data.IDbCommand iCmd = GetCommand(SqlString, iConn))
                {
                    iConn.Open();
                    try
                    {
                        object obj = iCmd.ExecuteScalar();
                        if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                        {
                            return null;
                        }
                        else
                        {
                            return obj;
                        }
                    }
                    catch
                    {
                        return null;
                    }
                    finally
                    {
                        if (iConn.State != ConnectionState.Closed)
                        {
                            iConn.Close();
                        }
                    }
                }
            }
        }

        public SqlDataReader GetDataReader(string SqlString)
        {
            using (SqlCommand tmpcmd = new SqlCommand(SqlString,MyCon))
            {
                try
                {
                    SqlDataReader sqldr = null;
                    sqldr = tmpcmd.ExecuteReader(CommandBehavior.CloseConnection);
                    return sqldr;
                }
                catch
                {
                    return null;
                }
            }
        }

        //public static SqlDataReader OleOperatorSql2(string Sqlstr) //返回数据集
        //{

        //    SqlDataReader sqldr = null;
        //    SqlConnection m_SqlConnection1;
        //    m_SqlConnection1 = new SqlConnection(sqlcontect);
        //    m_SqlConnection1.Open();
        //    SqlCommand m_olecm = new SqlCommand(Sqlstr, m_SqlConnection1);
        //    sqldr = m_olecm.ExecuteReader(CommandBehavior.CloseConnection);
        //    return sqldr;

        //}


        /**/
        /// <summary>
        /// 执行查询语句，返回IDataAdapter
        /// </summary>
        /// <param name="strSQL">查询语句</param>
        /// <returns>IDataAdapter</returns>
        public IDataAdapter ExecuteReader(string strSQL)
        {
            using (System.Data.IDbConnection iConn = this.GetConnection())
            {
                iConn.Open();
                try
                {
                    System.Data.IDataAdapter iAdapter = this.GetAdapater(strSQL, iConn);
                    return iAdapter;
                }
                catch (System.Exception e)
                {
                    throw new Exception(e.Message);
                }
                finally
                {
                    if (iConn.State != ConnectionState.Closed)
                    {
                        iConn.Close();
                    }
                }
            }
        }
        /**/
        /// <summary>
        /// 执行查询语句，返回DataSet
        /// </summary>
        /// <param name="SQLString">查询语句</param>
        /// <returns>DataSet</returns>
        public DataSet Query(string sqlString)
        {
            using (System.Data.IDbConnection iConn = this.GetConnection())
            {
                using (System.Data.IDbCommand iCmd = GetCommand(sqlString, iConn))
                {
                    DataSet ds = new DataSet();
                    iConn.Open();
                    try
                    {
                        System.Data.IDataAdapter iAdapter = this.GetAdapater(sqlString, iConn);
                        iAdapter.Fill(ds);
                        return ds;
                    }
                    catch (System.Exception ex)
                    {
                        throw new Exception(ex.Message);
                    }
                    finally
                    {
                        if (iConn.State != ConnectionState.Closed)
                        {
                            iConn.Close();
                        }
                    }
                }
            }
        }

        /**/
        /// <summary>
        /// 执行查询语句，向XML文件写入数据
        /// </summary>
        /// <param name="sqlString">查询语句</param>
        /// <param name="xmlPath">XML文件路径</param>
        public void WriteToXml(string sqlString, string xmlPath)
        {
            Query(sqlString).WriteXml(xmlPath);
        }

        /**/
        /// <summary>
        /// 执行查询语句
        /// </summary>
        /// <param name="SqlString">查询语句</param>
        /// <returns>DataTable </returns>
        public DataTable SelectDt(string sqlString)
        {
            using (System.Data.IDbConnection iConn = this.GetConnection())
            {
                DataSet ds = new DataSet();
                try
                {
                    System.Data.IDataAdapter iAdapter = this.GetAdapater(sqlString, iConn);
                    iAdapter.Fill(ds);

                    return ds.Tables[0];
                }
                catch (System.Exception e)
                {
                    //throw new Exception(e.Message);
                    MessageBox.Show(e.Message.ToString(), "数据库连接异常");
                }
                finally
                {
                    if (iConn.State != ConnectionState.Closed)
                    {
                        iConn.Close();
                    }
                }
                return null;
            }
        }


        /// <summary>
        /// 获取返回行数
        /// </summary>
        /// <param name="sqlString"></param>
        /// <returns></returns>
        public int CountRows(string sqlString)
        {
            using (System.Data.IDbConnection iConn = this.GetConnection())
            {
                DataSet ds = new DataSet();
                try
                {
                    System.Data.IDataAdapter iAdapter = this.GetAdapater(sqlString, iConn);
                    iAdapter.Fill(ds);
                }
                catch (System.Exception e)
                {
                    MessageBox.Show("数据表查询失败！请检查和服务器之间的网络！");
                }
                finally
                {
                    if (iConn.State != ConnectionState.Closed)
                    {
                        iConn.Close();
                    }
                }
                if (ds.Tables[0] != null)
                {
                    return ds.Tables[0].Rows.Count;
                }
                else
                {
                    return 0;
                }
            }
        }


        /// <summary>
        /// 判断某行记录是否为空  为空返回true
        /// </summary>
        /// <param name="sqlString"></param>
        /// <returns></returns>
        public bool CheckFieldNull(string sqlString)
        {
            using (System.Data.IDbConnection iConn = this.GetConnection())
            {
                DataSet ds = new DataSet();
                try
                {
                    System.Data.IDataAdapter iAdapter = this.GetAdapater(sqlString, iConn);
                    iAdapter.Fill(ds);
                }
                catch (System.Exception e)
                {
                    MessageBox.Show("数据表查询失败！请检查和服务器之间的网络！");
                }
                finally
                {
                    if (iConn.State != ConnectionState.Closed)
                    {
                        iConn.Close();
                    }
                }
                if (ds.Tables[0] != null && ds.Tables[0].Rows.Count == 1 && ds.Tables[0].Rows[0][0].ToString() == "")
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }



        /**/
        /// <summary>
        /// 执行查询语句
        /// </summary>
        /// <param name="SqlString">查询语句</param>
        /// <returns>DataTable </returns>
        public DataTable ExecuteQuery(string SqlString, string Proc)
        {
            using (System.Data.IDbConnection iConn = this.GetConnection())
            {
                using (System.Data.IDbCommand iCmd = GetCommand(SqlString, iConn))
                {
                    iCmd.CommandType = CommandType.StoredProcedure;
                    DataSet ds = new DataSet();
                    try
                    {
                        System.Data.IDataAdapter iDataAdapter = this.GetAdapater(SqlString, iConn);
                        iDataAdapter.Fill(ds);
                    }
                    catch (System.Exception e)
                    {
                        throw new Exception(e.Message);
                    }
                    finally
                    {
                        if (iConn.State != ConnectionState.Closed)
                        {
                            iConn.Close();
                        }
                    }
                    return ds.Tables[0];
                }


            }
        }

        /**/
        /// <summary>
        /// 
        /// </summary>
        /// <param name="Sql"></param>
        /// <returns></returns>
        public DataView ExeceuteDataView(string Sql)
        {
            using (System.Data.IDbConnection iConn = this.GetConnection())
            {
                using (System.Data.IDbCommand iCmd = GetCommand(Sql, iConn))
                {
                    DataSet ds = new DataSet();
                    try
                    {
                        System.Data.IDataAdapter iDataAdapter = this.GetAdapater(Sql, iConn);
                        iDataAdapter.Fill(ds);
                        return ds.Tables[0].DefaultView;
                    }
                    catch (System.Exception e)
                    {
                        throw new Exception(e.Message);
                    }
                    finally
                    {
                        if (iConn.State != ConnectionState.Closed)
                        {
                            iConn.Close();
                        }
                    }
                }
            }
        }

        #endregion

        #region 执行带参数的SQL语句
        /**/
        /// <summary>
        /// 执行SQL语句，返回影响的记录数
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public int ExecuteSql(string SQLString, params IDataParameter[] iParms)
        {
            using (System.Data.IDbConnection iConn = this.GetConnection())
            {
                System.Data.IDbCommand iCmd = GetCommand();
                {
                    try
                    {
                        PrepareCommand(out iCmd, iConn, null, SQLString, iParms);
                        int rows = iCmd.ExecuteNonQuery();
                        iCmd.Parameters.Clear();
                        return rows;
                    }
                    catch (System.Exception E)
                    {
                        throw new Exception(E.Message);
                    }
                    finally
                    {
                        iCmd.Dispose();
                        if (iConn.State != ConnectionState.Closed)
                        {
                            iConn.Close();
                        }
                    }
                }
            }
        }


        /**/
        /// <summary>
        /// 执行多条SQL语句，实现数据库事务。
        /// </summary>
        /// <param name="SQLStringList">SQL语句的哈希表（key为sql语句，value是该语句的SqlParameter[]）</param>
        public void ExecuteSqlTran(Hashtable SQLStringList)
        {
            using (System.Data.IDbConnection iConn = this.GetConnection())
            {
                iConn.Open();
                using (IDbTransaction iTrans = iConn.BeginTransaction())
                {
                    System.Data.IDbCommand iCmd = GetCommand();
                    try
                    {
                        //循环
                        foreach (DictionaryEntry myDE in SQLStringList)
                        {
                            string cmdText = myDE.Key.ToString();
                            IDataParameter[] iParms = (IDataParameter[])myDE.Value;
                            PrepareCommand(out iCmd, iConn, iTrans, cmdText, iParms);
                            int val = iCmd.ExecuteNonQuery();
                            iCmd.Parameters.Clear();
                        }
                        iTrans.Commit();
                    }
                    catch
                    {
                        iTrans.Rollback();
                        throw;
                    }
                    finally
                    {
                        iCmd.Dispose();
                        if (iConn.State != ConnectionState.Closed)
                        {
                            iConn.Close();
                        }
                    }

                }
            }
        }


        /**/
        /// <summary>
        /// 执行一条计算查询结果语句，返回查询结果（object）。
        /// </summary>
        /// <param name="SQLString">计算查询结果语句</param>
        /// <returns>查询结果（object）</returns>
        public object GetSingle(string SQLString, params IDataParameter[] iParms)
        {
            using (System.Data.IDbConnection iConn = this.GetConnection())
            {
                System.Data.IDbCommand iCmd = GetCommand();
                {
                    try
                    {
                        PrepareCommand(out iCmd, iConn, null, SQLString, iParms);
                        object obj = iCmd.ExecuteScalar();
                        iCmd.Parameters.Clear();
                        if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                        {
                            return null;
                        }
                        else
                        {
                            return obj;
                        }
                    }
                    catch (System.Exception e)
                    {
                        throw new Exception(e.Message);
                    }
                    finally
                    {
                        iCmd.Dispose();
                        if (iConn.State != ConnectionState.Closed)
                        {
                            iConn.Close();
                        }
                    }
                }
            }
        }

        /**/
        /// <summary>
        /// 执行查询语句，返回IDataReader
        /// </summary>
        /// <param name="strSQL">查询语句</param>
        /// <returns> IDataReader </returns>
        public IDataReader ExecuteReader(string SQLString, params IDataParameter[] iParms)
        {
            System.Data.IDbConnection iConn = this.GetConnection();
            {
                System.Data.IDbCommand iCmd = GetCommand();
                {
                    try
                    {
                        PrepareCommand(out iCmd, iConn, null, SQLString, iParms);
                        System.Data.IDataReader iReader = iCmd.ExecuteReader();
                        iCmd.Parameters.Clear();
                        return iReader;
                    }
                    catch (System.Exception e)
                    {
                        throw new Exception(e.Message);
                    }
                    finally
                    {
                        iCmd.Dispose();
                        if (iConn.State != ConnectionState.Closed)
                        {
                            iConn.Close();
                        }
                    }
                }
            }
        }

        /**/
        /// <summary>
        /// 执行查询语句，返回DataSet
        /// </summary>
        /// <param name="SQLString">查询语句</param>
        /// <returns>DataSet</returns>
        public DataSet Query(string sqlString, params IDataParameter[] iParms)
        {
            using (System.Data.IDbConnection iConn = this.GetConnection())
            {
                IDbCommand iCmd = GetCommand();
                {
                    PrepareCommand(out iCmd, iConn, null, sqlString, iParms);
                    try
                    {
                        IDataAdapter iAdapter = this.GetAdapater(sqlString, iConn);
                        DataSet ds = new DataSet();
                        iAdapter.Fill(ds);
                        iCmd.Parameters.Clear();
                        return ds;
                    }
                    catch (System.Exception ex)
                    {
                        throw new Exception(ex.Message);
                    }
                    finally
                    {
                        iCmd.Dispose();
                        if (iConn.State != ConnectionState.Closed)
                        {
                            iConn.Close();
                        }
                    }
                }
            }
        }


        /**/
        /// <summary>
        /// 初始化Command
        /// </summary>
        /// <param name="iCmd"></param>
        /// <param name="iConn"></param>
        /// <param name="iTrans"></param>
        /// <param name="cmdText"></param>
        /// <param name="iParms"></param>
        private void PrepareCommand(out IDbCommand iCmd, IDbConnection iConn, System.Data.IDbTransaction iTrans, string cmdText, IDataParameter[] iParms)
        {
            if (iConn.State != ConnectionState.Open)
                iConn.Open();
            iCmd = this.GetCommand();
            iCmd.Connection = iConn;
            iCmd.CommandText = cmdText;
            if (iTrans != null)
                iCmd.Transaction = iTrans;
            iCmd.CommandType = CommandType.Text;//cmdType;
            if (iParms != null)
            {
                foreach (IDataParameter parm in iParms)
                    iCmd.Parameters.Add(parm);
            }
        }

        #endregion

        #region 存储过程操作

        /**/
        /// <summary>
        /// 执行存储过程
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <returns>SqlDataReader</returns>
        public SqlDataReader RunProcedure(string storedProcName, IDataParameter[] parameters)
        {
            System.Data.IDbConnection iConn = this.GetConnection();
            {
                iConn.Open();

                using (SqlCommand sqlCmd = BuildQueryCommand(iConn, storedProcName, parameters))
                {
                    return sqlCmd.ExecuteReader(CommandBehavior.CloseConnection);
                }
            }
        }

        /**/
        /// <summary>
        /// 执行存储过程
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <param name="tableName">DataSet结果中的表名</param>
        /// <returns>DataSet</returns>
        public DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName)
        {

            using (System.Data.IDbConnection iConn = this.GetConnection())
            {
                DataSet dataSet = new DataSet();
                iConn.Open();
                System.Data.IDataAdapter iDA = this.GetAdapater();
                iDA = this.GetAdapater(BuildQueryCommand(iConn, storedProcName, parameters));

                ((SqlDataAdapter)iDA).Fill(dataSet, tableName);
                if (iConn.State != ConnectionState.Closed)
                {
                    iConn.Close();
                }
                return dataSet;
            }
        }



        /**/
        /// <summary>
        /// 执行存储过程
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <param name="tableName">DataSet结果中的表名</param>
        /// <param name="startIndex">开始记录索引</param>
        /// <param name="pageSize">页面记录大小</param>
        /// <returns>DataSet</returns>
        public DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, int startIndex, int pageSize, string tableName)
        {

            using (System.Data.IDbConnection iConn = this.GetConnection())
            {
                DataSet dataSet = new DataSet();
                iConn.Open();
                System.Data.IDataAdapter iDA = this.GetAdapater();
                iDA = this.GetAdapater(BuildQueryCommand(iConn, storedProcName, parameters));

                ((SqlDataAdapter)iDA).Fill(dataSet, startIndex, pageSize, tableName);
                if (iConn.State != ConnectionState.Closed)
                {
                    iConn.Close();
                }
                return dataSet;
            }
        }

        /**/
        /// <summary>
        /// 执行存储过程 填充已经存在的DataSet数据集 
        /// </summary>
        /// <param name="storeProcName">存储过程名称</param>
        /// <param name="parameters">存储过程参数</param>
        /// <param name="dataSet">要填充的数据集</param>
        /// <param name="tablename">要填充的表名</param>
        /// <returns></returns>
        public DataSet RunProcedure(string storeProcName, IDataParameter[] parameters, DataSet dataSet, string tableName)
        {
            using (System.Data.IDbConnection iConn = this.GetConnection())
            {
                iConn.Open();
                System.Data.IDataAdapter iDA = this.GetAdapater();
                iDA = this.GetAdapater(BuildQueryCommand(iConn, storeProcName, parameters));

                ((SqlDataAdapter)iDA).Fill(dataSet, tableName);

                if (iConn.State != ConnectionState.Closed)
                {
                    iConn.Close();
                }

                return dataSet;
            }
        }

        /**/
        /// <summary>
        /// 执行存储过程并返回受影响的行数
        /// </summary>
        /// <param name="storedProcName"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public int RunProcedureNoQuery(string storedProcName, IDataParameter[] parameters)
        {

            int result = 0;
            using (System.Data.IDbConnection iConn = this.GetConnection())
            {
                iConn.Open();
                using (SqlCommand scmd = BuildQueryCommand(iConn, storedProcName, parameters))
                {
                    result = scmd.ExecuteNonQuery();
                }

                if (iConn.State != ConnectionState.Closed)
                {
                    iConn.Close();
                }
            }

            return result;
        }

        public string RunProcedureExecuteScalar(string storeProcName, IDataParameter[] parameters)
        {
            string result = string.Empty;
            using (System.Data.IDbConnection iConn = this.GetConnection())
            {

                iConn.Open();
                using (SqlCommand scmd = BuildQueryCommand(iConn, storeProcName, parameters))
                {
                    object obj = scmd.ExecuteScalar();
                    if (obj == null)
                        result = null;
                    else
                        result = obj.ToString();
                }

                if (iConn.State != ConnectionState.Closed)
                {
                    iConn.Close();
                }

            }

            return result;
        }

        /**/
        /// <summary>
        /// 构建 SqlCommand 对象(用来返回一个结果集，而不是一个整数值)
        /// </summary>
        /// <param name="connection">数据库连接</param>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <returns>SqlCommand</returns>
        private SqlCommand BuildQueryCommand(IDbConnection iConn, string storedProcName, IDataParameter[] parameters)
        {

            IDbCommand iCmd = GetCommand(storedProcName, iConn);
            iCmd.CommandType = CommandType.StoredProcedure;
            if (parameters == null)
            {
                return (SqlCommand)iCmd;
            }
            foreach (IDataParameter parameter in parameters)
            {
                iCmd.Parameters.Add(parameter);
            }
            return (SqlCommand)iCmd;
        }

        /**/
        /// <summary>
        /// 执行存储过程，返回影响的行数        
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <param name="rowsAffected">影响的行数</param>
        /// <returns></returns>
        public int RunProcedure(string storedProcName, IDataParameter[] parameters, out int rowsAffected)
        {
            using (System.Data.IDbConnection iConn = this.GetConnection())
            {
                int result;
                iConn.Open();
                using (SqlCommand sqlCmd = BuildIntCommand(iConn, storedProcName, parameters))
                {
                    rowsAffected = sqlCmd.ExecuteNonQuery();
                    result = (int)sqlCmd.Parameters["ReturnValue"].Value;

                    if (iConn.State != ConnectionState.Closed)
                    {
                        iConn.Close();
                    }
                    return result;
                }
            }
        }

        /**/
        /// <summary>
        /// 创建 SqlCommand 对象实例(用来返回一个整数值)    
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <returns>SqlCommand 对象实例</returns>
        private SqlCommand BuildIntCommand(IDbConnection iConn, string storedProcName, IDataParameter[] parameters)
        {
            SqlCommand sqlCmd = BuildQueryCommand(iConn, storedProcName, parameters);
            sqlCmd.Parameters.Add(new SqlParameter("ReturnValue",
                SqlDbType.Int, 4, ParameterDirection.ReturnValue,
                false, 0, 0, string.Empty, DataRowVersion.Default, null));
            return sqlCmd;
        }
        #endregion    


        /* ************************************************************************
         * 修改人:ken               日期:2008-07-22
         * 说明:  执行存储过程IsPaperIdExist,查看是否已经存在试卷ID
         * ************************************************************************/
        public bool IsPaperIdExist(String paperId)
        {
            int output = 0;
            SqlConnection conn = null;
            try
            {
                conn = new SqlConnection(ConnStr);
                conn.Open();
                SqlCommand sqlCmd = new SqlCommand("IsPaperIdExist", conn);
                sqlCmd.CommandType = CommandType.StoredProcedure;

                SqlParameter paramPaperId = new SqlParameter("@paperid", SqlDbType.Char, 1);
                paramPaperId.Value = paperId;
                SqlParameter paramOutput = new SqlParameter("@output", SqlDbType.Int, 4);
                paramOutput.Direction = ParameterDirection.Output;
                sqlCmd.Parameters.Add(paramPaperId);
                sqlCmd.Parameters.Add(paramOutput);

                sqlCmd.ExecuteNonQuery();
                output = (int)paramOutput.Value;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                if (conn != null)
                    conn.Close();
                return false;
            }
            finally
            {
                if (conn != null)
                    conn.Close();
            }
            if (output == 1)     //output=1表示PaperId不存在
                return false;
            else
                return true;
        }


        /* ************************************************************************
         * 修改人:ken               日期:2008-07-22
         * 说明:  执行存储过程IsTestIdExist,查看是否已经存在试题ID
         * ************************************************************************/
        public bool IsTestIdExist(String testId)
        {
            int output = 0;
            SqlConnection conn = null;
            try
            {
                conn = new SqlConnection(ConnStr);
                conn.Open();
                SqlCommand sqlCmd = new SqlCommand("IsTestIdExist", conn);
                sqlCmd.CommandType = CommandType.StoredProcedure;

                SqlParameter paramTestId = new SqlParameter("@testid", SqlDbType.Int, 4);
                paramTestId.Value = Int32.Parse(testId);
                SqlParameter paramOutput = new SqlParameter("@output", SqlDbType.Int, 4);
                paramOutput.Direction = ParameterDirection.Output;
                sqlCmd.Parameters.Add(paramTestId);
                sqlCmd.Parameters.Add(paramOutput);

                sqlCmd.ExecuteNonQuery();
                output = (int)paramOutput.Value;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                if (conn != null)
                    conn.Close();
                return false;
            }
            finally
            {
                if (conn != null)
                    conn.Close();
            }
            if (output == 1)     //output=1表示PaperId不存在
                return false;
            else
                return true;
        }

        /* ************************************************************************
         * 修改人:ken               日期:2008-07-22
         * 说明:  执行存储过程PaperTest,查看在表tblPaper_Test中是否已经存在试题ID
         * ************************************************************************/

        public bool PaperTest(String TestId)
        {
            int output = 0;
            SqlConnection conn = null;
            try
            {
                conn = new SqlConnection(ConnStr);
                conn.Open();
                SqlCommand sqlCmd = new SqlCommand("PaperTest", conn);
                sqlCmd.CommandType = CommandType.StoredProcedure;

                SqlParameter testIdParam = new SqlParameter("@testId", SqlDbType.Int, 4);
                testIdParam.Value = Int32.Parse(TestId);
                SqlParameter outputParam = new SqlParameter("@output", SqlDbType.Int, 4);
                outputParam.Direction = ParameterDirection.Output;

                sqlCmd.Parameters.Add(testIdParam);
                sqlCmd.Parameters.Add(outputParam);
                sqlCmd.ExecuteNonQuery();

                output = (int)outputParam.Value;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                if (conn != null)
                    conn.Close();
            }
            {
                if (conn != null)
                    conn.Close();
            }
            if (output == 1)
                return true;
            else
                return false;
        }
   
    
    }
}